package com.lwp.demo.controller;

import com.lwp.demo.service.ServerLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author kaka
 */
@Controller
@RequestMapping("/main")
public class MainController {
    @Resource
    private ServerLoginService serverLoginService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    private Logger logger=LoggerFactory.getLogger(MainController.class);
    @RequestMapping("/loginPage")
    public String loginPageFunc() {
        return "login";
    }

    @RequestMapping("/checkToken")
    @ResponseBody
    public String checkToken(HttpServletRequest req , HttpServletResponse res){
        String token=req.getParameter("token");
        logger.info("check token :" + token);
        if(redisTemplate.opsForValue().get(token)!=null){
            logger.info("token pass");
            return "true";
        }
        else {
            return "false";
        }
    }
    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest req , HttpServletResponse res) throws IOException {
        logger.info("开始登陆校验");
        if (serverLoginService.checkLoginInfo(username, password)){
            req.getSession().setAttribute("isLogin", true);
            String token = UUID.randomUUID().toString();
            if (redisTemplate==null){
                logger.error("redisTemplate is null");
            }
            logger.info("生成 token:"+token);
            redisTemplate.opsForValue().set(token,token,30, TimeUnit.MINUTES);
            res.sendRedirect("/server/login?token="+token);
        }
        return loginPageFunc();
    }
}
